﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Resources;

namespace GenericValidation
{
    /// <summary>
    /// Resolves Validation Message, according to a message template and the list of parameters, determined at validation time.
    /// Validation parameters may be either objects either Lambda Expressions (delegates) that are evaluated at validation time,
    /// therefore making it possible to add validated values, and any other object member values.
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class ValidationMessage<T>
    {
        internal ValidationMessage(IValidation rule)
        {
            this.Validation = rule;
        }

        public IValidation Validation { get; set; }

        public string ErrorTemplate { get; set; }

        public Expression<Func<T, object>>[] ErrorParams { get; set; }

        public object[] Args { get; set; }

        public string GetErrorMessage(T item)
        {
            var theResult = this.Validation.LocalizeMessage(this.ErrorTemplate);
            if ((this.Args == null || this.Args.Length == 0) && this.ErrorParams != null)
            {
                var args = from p in this.ErrorParams
                           select p.Compile()(item);

                this.Args = args.ToArray();

            }

            theResult = string.Format(theResult, this.Args);

            return theResult;
        }

    }
}
